import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, Select, message, Popconfirm, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, LockOutlined } from '@ant-design/icons';

const { Option } = Select;

// API 基础URL
const API_BASE_URL = 'http://localhost:3001';

const UserManagement = () => {
  const [userList, setUserList] = useState([]);
  const [roleList, setRoleList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加用户');
  const [form] = Form.useForm();
  const [currentId, setCurrentId] = useState(null);

  // 获取用户列表
  const fetchUserList = async () => {
    setLoading(true);
    try {
      // 模拟从API获取数据
      setTimeout(() => {
        const mockUsers = [
          { id: 1, username: 'admin', nickname: '管理员', email: 'admin@example.com', roleId: 1, status: 1 },
          { id: 2, username: 'user1', nickname: '普通用户1', email: 'user1@example.com', roleId: 2, status: 1 },
          { id: 3, username: 'user2', nickname: '普通用户2', email: 'user2@example.com', roleId: 2, status: 0 },
        ];
        setUserList(mockUsers.map(item => ({ ...item, key: item.id })));
        setLoading(false);
      }, 500);
    } catch (error) {
      message.error('获取用户列表失败');
      console.error(error);
      setLoading(false);
    }
  };

  // 获取角色列表
  const fetchRoleList = async () => {
    try {
      // 模拟从API获取数据
      setTimeout(() => {
        const mockRoles = [
          { id: 1, name: '管理员' },
          { id: 2, name: '普通用户' },
          { id: 3, name: '访客' },
        ];
        setRoleList(mockRoles);
      }, 300);
    } catch (error) {
      message.error('获取角色列表失败');
      console.error(error);
    }
  };

  useEffect(() => {
    fetchUserList();
    fetchRoleList();
  }, []);

  // 添加或更新用户
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (currentId) {
        // 模拟更新用户
        const updatedList = userList.map(item => 
          item.id === currentId ? { ...item, ...values } : item
        );
        setUserList(updatedList);
        message.success('更新成功');
      } else {
        // 模拟添加用户
        const newUser = {
          id: Date.now(),
          ...values,
          status: values.status || 1
        };
        setUserList([...userList, { ...newUser, key: newUser.id }]);
        message.success('添加成功');
      }
      setModalVisible(false);
    } catch (error) {
      console.error('提交表单失败:', error);
    }
  };

  // 删除用户
  const handleDelete = (id) => {
    // 模拟删除用户
    const updatedList = userList.filter(item => item.id !== id);
    setUserList(updatedList);
    message.success('删除成功');
  };

  // 打开添加用户模态框
  const showAddModal = () => {
    setModalTitle('添加用户');
    setCurrentId(null);
    form.resetFields();
    form.setFieldsValue({ status: 1 });
    setModalVisible(true);
  };

  // 打开编辑用户模态框
  const showEditModal = (record) => {
    setModalTitle('编辑用户');
    setCurrentId(record.id);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  // 表格列配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username'
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email'
    },
    {
      title: '角色',
      dataIndex: 'roleId',
      key: 'roleId',
      render: (roleId) => {
        const role = roleList.find(role => role.id === roleId);
        return role ? role.name : '-';
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="primary" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={showAddModal}
        >
          添加用户
        </Button>
      </div>
      
      <Table 
        columns={columns} 
        dataSource={userList} 
        loading={loading}
        pagination={{ pageSize: 10 }}
        rowKey="id"
      />
      
      <Modal
        title={modalTitle}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ status: 1 }}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          
          {!currentId && (
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" prefix={<LockOutlined />} />
            </Form.Item>
          )}
          
          <Form.Item
            name="nickname"
            label="昵称"
            rules={[{ required: true, message: '请输入昵称' }]}
          >
            <Input placeholder="请输入昵称" />
          </Form.Item>
          
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          
          <Form.Item
            name="roleId"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select placeholder="请选择角色">
              {roleList.map(role => (
                <Option key={role.id} value={role.id}>{role.name}</Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
          >
            <Select>
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;